package cn.chenc.framework.security.handle;

import cn.chenc.framework.core.component.AbstractJwtTemplate;
import cn.chenc.framework.core.consts.HttpStatus;
import cn.chenc.framework.core.model.AbstractLoginUser;
import cn.chenc.framework.core.model.request.RequestHolder;
import cn.chenc.framework.core.model.response.AjaxResult;
import cn.chenc.framework.core.util.JsonUtils;
import cn.chenc.framework.core.util.StringUtils;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;

import java.io.IOException;

/**
 * 自定义退出处理类 返回成功
 *
 * @author secret
 */
@Configuration
public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(LogoutSuccessHandlerImpl.class);

    @Autowired
    private AbstractJwtTemplate tokenService;

    /**
     * 退出处理
     *
     * @return
     */
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        AbstractLoginUser loginUser = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(loginUser)) {
            String userName = loginUser.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(loginUser.getToken());
            // 记录用户退出日志
            LOGGER.info("退出成功");
        }
        RequestHolder.renderString(response, JsonUtils.objectToJson(AjaxResult.error(HttpStatus.SUCCESS, "退出成功")));
    }
}
